package com.hfdg.prototype.base.init;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName DictionaryInitInRedis
 * @Description TODO
 * @Author yuelh
 * @Date 2020-3-18 11:13
 * @Version 1.0
 * @Company 会飞的锅工作室
 **/
@Component
@Order(2)
public class DictionaryInitInRedis implements ApplicationRunner {
    Logger logger = LoggerFactory.getLogger(DictionaryInitInRedis.class);
    @Autowired
    JdbcTemplate jdbcTemplate;
    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        logger.info("字典缓存初始化开始...");
        String sql ="SELECT\n" +
                "dic_dictionary.category,\n" +
                "dic_dictionary.`VALUE` as value,\n" +
                "dic_dictionary.text\n" +
                "FROM\n" +
                "dic_dictionary\n" +
                "ORDER BY\n" +
                "dic_dictionary.sort_no ASC";
        List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
        Map<String,List<Map<String,Object>>> dic = new HashMap<>();
        for(Map<String,Object> map:list){
            if(null==dic.get(map.get("category")+"")){
                List<Map<String,Object>> data = new ArrayList<>();
                dic.put(map.get("category")+"",data);
            }
        }

        for(Map<String,Object> map:list){
            dic.get(map.get("category")+"").add(map);
        }
        for(String key:dic.keySet()){
            redisTemplate.opsForValue().set(key,dic.get(key));
        }
        logger.info("字典缓存初始化结束...");

    }
}
